<template>
    <div id="release">
        <van-cell-group inset class="mt20">
            <van-field v-model="goodInfo.title" center label="标题" placeholder="请输入装备标题" label-align="top" rows="1" autosize type="textarea" maxlength="150" show-word-limit />
        </van-cell-group>
        <van-cell-group inset class="mt20">
            <van-field v-model="goodInfo.description" center label="描述" placeholder="请输入装备描述" label-align="top" rows="2" autosize type="textarea" maxlength="255" show-word-limit />
        </van-cell-group>
        <van-cell-group inset class="mt20">
            <van-cell title="装备图片">
                <template #label>
                    <van-uploader :before-read="beforeRead" :after-read="afterRead" :before-delete="beforeDelete" v-model="fileList" multiple :max-count="maxSize" />
                </template>
            </van-cell>
        </van-cell-group>
        <van-cell-group inset class="mt20">
            <van-field v-model="goodInfo.price" center input-align="right" type="number" label="价格" placeholder="请输入装备价格">
                <template #left-icon>
                    <img src="/statics/home/images/price.png" class="release-img" alt="price">
                </template>
                <template #extra>
                    <span class="ml10">元</span>
                </template>
            </van-field>
        </van-cell-group>
        <van-cell-group inset class="mt20">
            <van-field v-model="goodInfo.username" center input-align="right" label="账号" placeholder="请输入登录账号">
                <template #left-icon>
                    <img src="/statics/home/images/account.png" class="release-img" alt="price">
                </template>
            </van-field>
        </van-cell-group>
        <van-cell-group inset class="mt20">
            <van-field v-model="goodInfo.rolename" center input-align="right" label="角色" placeholder="请输入装备所在角色名">
                <template #left-icon>
                    <img src="/statics/home/images/account.png" class="release-img" alt="price">
                </template>
            </van-field>
        </van-cell-group>
        <van-cell-group inset class="mt20">
            <van-field v-model="goodInfo.password" center input-align="right" label="密码" placeholder="请输入登录密码">
                <template #left-icon>
                    <img src="/statics/home/images/pwd.png" class="release-img" alt="price">
                </template>
            </van-field>
        </van-cell-group>
        <div class="con-wrap">
            <div class="btn-1 btn-1-main mt50" @click="toSubmit()">发布</div>
        </div>
    </div>
</template>


<script>
import Compressor from 'compressorjs';
export default {
    name: 'Release',
    data() {
        return {
            detail_id:0,
            fileList:[],
            fileUrl:[],
            goodInfo: {
                title: '',
                description: '',
                album:[],
                price:'',
                username:'',
                password:'',
                rolename:'',
            },
            maxSize:10,
        }
    },
    created() { 
        this.detail_id = this.$route.params.id == undefined ? 0 : this.$route.params.id;
        if(this.detail_id != 0){
            let that = this;
            this.$api.good.detail({detail_id:this.detail_id}).then(res => {
                that.goodInfo = res.result;
                res.result.album.forEach(item => {
                    that.fileList.push({url:item});
                    that.fileUrl.push(item);
                })
            }).finally(e=>{});
        }
    },
    methods: {
        async toSubmit() {
            // 新建||修改
            let params = this.goodInfo;
            params.album = this.fileUrl;
            if(this.detail_id == 0){
                this.$api.good.create(params).then(res => {
                    this.$router.go(-1);
                }).finally(e=>{});
            }else{
                params.detail_id = this.detail_id;
                this.$api.good.update(params).then(res => {
                    this.$router.go(-1);
                }).finally(e=>{});
            }
        },
        // 检查数量等
        beforeRead(file) {
            let This = this
            if (Array.isArray(file)) {
                if (file.length > This.maxSize) {
                    This.$toast("超过最大上传张数！")
                    return false
                }
                file.forEach(item => {
                    if (!item.type.startsWith('image')){
                        this.$toast("请上传图片！")
                        return false
                    }else if(item.size > 1024*1024*5){
                        this.$toast("图片超过5M！")
                        return false
                    }
                })
            } else {
                if (!file.type.startsWith('image')){
                    this.$toast("请上传图片！")
                    return false
                }
                if(file.size > 1024*1024*5){
                    this.$toast("图片超过5M！")
                    return false
                }
            }
            return true
        },
        // 文件读取成功的操作，只压缩，不上传
        afterRead(file){
            // console.log('afterRead',file)
            let This = this
            if(Array.isArray(file)){
                file.forEach((item) => {
                    item.status = 'uploading'
                    item.message = '上传中...'
                    This.uploadImages(item)
                })
            }else {
                file.status = 'uploading'
                file.message = '上传中...'
                This.uploadImages(file)
            }
        },
        beforeDelete(file,index){
            this.fileUrl.splice(index,1);
            return true;
        },
        // 单个图片上传
        async uploadImages(imgFile){
            let file = await this.compressFile(imgFile.file)
            this.$api.upload.image({imgFile:file}).then(res => {
                imgFile.message = '上传成功'
                imgFile.status = 'done';
                this.fileUrl.push(res.result.url);
            }).catch(error => {
                imgFile.status = 'failed'
                imgFile.message = '上传失败'
                this.$toast("照片上传失败，请重新上传！")
            }).finally(e => {})
        },
        // 压缩图片
        compressFile(file) {
            return new Promise((resolve, reject) => {
                new Compressor(file, {
                    quality: 0.6, //压缩质量
                    checkOrientation: true, //图片翻转，默认为true
                    success(result) {
                        // console.log('压缩成功',result)
                        resolve(result);
                    },
                    error(e) {
                        console.log('压缩失败',e)
                        reject()
                    }
                })
            })
        },
    }
}
</script>
